import {isEmpty} from "./CommonFunction";
import type from "./TypeUtil";
import stringUtil from "./StringUtil";

Number.prototype.toPencent = function (fixed) {
  if (0 == this) {
    return "0%";
  }
  let str = this;
  if (null != this) {
    str = Number(this * 100).toFixed(fixed || 1);
    str += "%";
  }
  return str;
}
Number.prototype.format = function (pattern) {
  if (isEmpty(pattern)) {
    return this;
  }
  let isPercent = pattern.endsWith("%");
  let num = this;
  if (isPercent === true) {
    num = this * 100.0;
    pattern = pattern.substring(0, pattern.length - 1);
  }
  let patternSubs = pattern ? pattern.split('.') : [''];
  let numArray = ['0'];
  if (patternSubs.length > 1) {
    numArray = Number(num).toFixed(patternSubs[1].length).split('.');
  } else {
    numArray = num.toString().split('.');
  }
  let retString = '';

  // 整数部分
  let str = numArray[0];
  let fmt = patternSubs[0];
  let i = str.length - 1;
  let comma = false;
  for (let f = fmt.length - 1; f >= 0; f--) {
    switch (fmt.substr(f, 1)) {
      case '#':
        if (i >= 0) {
          retString = str.substr(i--, 1) + retString;
        }
        break;
      case '0':
        if (i >= 0) {
          retString = str.substr(i--, 1) + retString;
        } else {
          retString = '0' + retString;
        }
        break;
      case ',':
        comma = true;
        retString = ',' + retString;
        break;
    }
  }
  if (i >= 0) {
    if (comma) {
      let l = str.length;
      for (; i >= 0; i--) {
        retString = str.substr(i, 1) + retString;
        if (i > 0 && ((l - i) % 3) == 0) retString = ',' + retString;
      }
    } else retString = str.substr(0, i + 1) + retString;
  }

  retString = retString + '.';
  // 处理小数部分
  str = numArray.length > 1 ? numArray[1] : '';
  fmt = patternSubs.length > 1 ? patternSubs[1] : '';
  i = 0;
  for (let f = 0; f < fmt.length; f++) {
    switch (fmt.substr(f, 1)) {
      case '#':
        if (i < str.length) {
          retString += str.substr(i++, 1);
        }
        break;
      case '0':
        if (i < str.length) {
          retString += str.substr(i++, 1);
        } else {
          retString += '0';
        }
        break;
    }
  }
  let result = retString.replace(/^,+/, '').replace(/\.$/, '');
  if (isPercent === true) {
    result = result + "%";
  }
  return result;
}


class NumberUtil {
  format(num, pattern) {
    if (isEmpty(num)) {
      return null;
    }
    return num.format(pattern);
  }

  toPercent(val) {
    if (type.isNumber(val)) {
      return val.toPencent();
    }
    if (type.isString(val) && stringUtil.isNumber(val)) {
      let num = val + 0;
      return num.toPencent();
    }
    return null;
  }
}

export default new NumberUtil();
